using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.IO;

namespace Crap4Net.CCParsers
{

    public class NCover3CCParser : ICCParser
    {
        private IList<CCDataEntry> _data = null;

        #region ICCParser

        public void LoadData(string reportFileName)
        {
            if (!File.Exists(reportFileName))
            {
                throw new ArgumentException("NCover 3.0 CC report file was not found: " + reportFileName);
            }
            Data = new List<CCDataEntry>();
            ParseDataFromXml(reportFileName);

        }

        public IList<CCDataEntry> Data
        {
            get
            {
                if (_data == null)
                    throw new ApplicationException("Data was not loaded");
                return _data;
            }
            private set
            {
                _data = value;
            }
        }
        #endregion

        private void ParseDataFromXml(string reportFileName)
        {
            IEnumerable<XElement> results = LoadMethodsDataFromFile(reportFileName);
            foreach (var method in results)
            {
                var parser = new NCoverMethodParser();
                var methodSignature = parser.ParseMethodSignature(method);
                int coverage = GetCCValue(method);

                Data.Add(new CCDataEntry(methodSignature, coverage));
            }
        }

        private IEnumerable<XElement> LoadMethodsDataFromFile(string reportFileName)
        {
            XDocument loaded = XDocument.Load(reportFileName);
            var result = (from metric in loaded.Descendants()
                          where metric.Name.LocalName == "method"
                          select metric);
            return result;
        }

        private int GetCCValue(XElement method)
        {
            return (int)method.Attribute("cc");
        }

    }
}
